import menuApi from '@/api/menu';

export function initMenu(router, store) {
    if (store.state.routes.routes.length > 0) {
        return;
    }
    menuApi.menuList().then(resp => {
        if (resp.data.flag) {
            let formatRouters = formatRoutes(resp.data.data);
            //formatRouters[0]为layout根布局组件
            //包含没有路由的一级菜单，存入vuex中，用于遍历生成 这里用JSON.parse防止下面修改时发生引用传递导致一开始的值也改变
            let allformatRouters = JSON.parse(
                JSON.stringify(formatRouters[0].children)
            );
            store.commit("INIT_ROUTES", allformatRouters);

            //去掉所有左侧没有路由的一级菜单存入vue-router
            formatRouters[0].children.forEach(r => {
                let removed = [];
                r.children = r.children.filter(item => {
                    if (item.meta.type === 0) {
                        removed.push(item.children);
                        return false;
                    } else {
                        return true;
                    }
                });
                // r.children.push(removed);
                removed.forEach(item => {
                    item.forEach(childRoute => {
                        r.children.push(childRoute);
                    });
                });
            });
            router.addRoutes(formatRouters);
            console.log(router);
        }
    });
}

export function formatRoutes(routes) {
    let formatRouters = [];
    routes.forEach(r => {
        let router = {
            path: r.path,
            name: r.code,
            redirect: r.redirect,
            meta: {title: r.name, type: r.type,icon:r.icon},
            component: r.component,
            children: r.children
        };
        if (router.children && router.children instanceof Array) {
            router.children = formatRoutes(router.children);
        }

        let formatRoute = {
            path: router.path,
            name: router.name,
            meta: {title: router.meta.title, type: router.meta.type,icon:router.meta.icon},
            component(resolve) {
                if (router.component && router.component==='layout') {
                    require(['../components/'+router.component+'.vue'], resolve);
                } else {
                    require(["@/views/" + router.component + ".vue"], resolve);
                }
            },
            children: router.children
        };

        if (router.redirect) {
            formatRoute.redirect = router.redirect;
        }
        formatRouters.push(formatRoute);
    });
    return formatRouters;
}
